package com.jasonjan.jiance.main

import android.app.Activity
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTransaction
import android.support.v4.widget.DrawerLayout
import android.support.v7.widget.Toolbar
import android.widget.Toast
import com.jasonjan.jiance.R
import com.jasonjan.jiance.module.base.BaseActivity
import com.jasonjan.jiance.module.home.HomeTabLayout
import com.jasonjan.jiance.module.me.MeTabLayout
import com.jasonjan.jiance.module.news.NewsTabLayout
import com.jasonjan.jiance.module.search.main.SearchTabLayout
import com.jasonjan.jiance.util.SettingUtil
import com.jasonjan.jiance.widget.BottomNavigationViewHelper

class MainActivity : BaseActivity() {

    companion object {
        private val TAG="MainActivity"
        private val POSITION="position"
        private val SELECT_ITEM="bottomNavigationSelectItem"
       /* private val FRAGMENT_NEWS=0*/
        private val FRAGMENT_PHOTO=0
        private val FRAGMENT_VIDEO=1
        private val FRAGMENT_MEDIA=2
        private val REQUEST_EXTERNAL_STORAGE = 1
        private val PERMISSIONS_STORAGE = arrayOf("android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE")

    }
    private var newsTabLayout: NewsTabLayout?=null   //新闻布局
    private var homeTabLayout: HomeTabLayout?=null     //图片布局
    private var searchTabLayout: SearchTabLayout?=null     //视频布局
    private var meTabLayout: MeTabLayout?=null    //头条号布局
    private var toolbar: Toolbar?=null    //标题栏
    private var bottom_navigation:BottomNavigationView?=null
    private var exitTime:Long=0
    private var position:Int=0
    private var firstClickTime:Long=0
   /* private var nav_view:NavigationView?=null*/
    private var drawer_layout:DrawerLayout?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        verifyStoragePermissions(this)
        if(savedInstanceState!=null){
          /*  newsTabLayout=supportFragmentManager!!.findFragmentByTag(NewsTabLayout::class.java.name) as NewsTabLayout*/
            homeTabLayout =supportFragmentManager!!.findFragmentByTag(HomeTabLayout::class.java.name) as HomeTabLayout
            searchTabLayout =supportFragmentManager!!.findFragmentByTag(SearchTabLayout::class.java.name) as SearchTabLayout
            meTabLayout =supportFragmentManager!!.findFragmentByTag(MeTabLayout::class.java.name) as MeTabLayout
            //恢复 recreate 前的位置
            showFragment(savedInstanceState.getInt(POSITION))
            bottom_navigation!!.selectedItemId=savedInstanceState.getInt(SELECT_ITEM)
        }else{
            showFragment(FRAGMENT_PHOTO)
        }

        if(SettingUtil.getInstance().getIsFirstTime()){
            //showTapTarget()
        }
    }

    /*private fun showTapTarget(){
        val display=windowManager.defaultDisplay
        val target=Rect(0,display.height,0,display.height)
        target.offset(display.width/8,-56)

        val sequence=TapTargetSequence(this)
                .targets(
                     TapTarget.forToolbarMenuItem(toolbar!!,R.id.action_search,"点击这里进行搜索")
                             .dimColor(android.R.color.black)
                             .outerCircleColor(R.color.colorPrimary)
                             .drawShadow(true)
                             .id(1),
                     TapTarget.forToolbarNavigationIcon(toolbar!!,"点击这里展开侧栏")
                             .dimColor(android.R.color.black)
                             .outerCircleColor(R.color.colorPrimary)
                             .drawShadow(true)
                             .id(2),
                     TapTarget.forBounds(target,"点击这里切换新闻\n再次点击刷新当前页面")
                             .dimColor(android.R.color.black)
                             .outerCircleColor(R.color.colorPrimary)
                             .targetRadius(60)
                             .transparentTarget(true)
                             .drawShadow(true)
                             .id(3)
                ).listener(object:TapTargetSequence.Listener{
            override fun onSequenceFinish() {
                SettingUtil.getInstance().isFirstTime=false
            }

            override fun onSequenceStep(lastTarget: TapTarget?, targetClicked: Boolean) {

            }

            override fun onSequenceCanceled(lastTarget: TapTarget?) {

            }
        })
        sequence.start()
    }*/

    override fun initSlidable() {
        //禁止滑动返回
        //什么都不写就行了
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        outState!!.putInt(POSITION,position)
        outState!!.putInt(SELECT_ITEM,bottom_navigation!!.selectedItemId)
    }

    private fun initView(){
        toolbar=findViewById(R.id.toolbar)
      /*  toolbar!!.inflateMenu(R.menu.menu_activity_main)*/
        bottom_navigation=findViewById(R.id.bottom_navigation)
        //解决只有图标没有文字的问题
        BottomNavigationViewHelper.disableShiftMode(bottom_navigation)
        setSupportActionBar(toolbar)
        setTitle(R.string.title_photo)
        bottom_navigation!!.setOnNavigationItemSelectedListener{ item ->
            when(item.itemId){

                R.id.action_photo -> {
                    showFragment(FRAGMENT_PHOTO)
                    doubleClick(FRAGMENT_PHOTO)
                }
                R.id.action_video -> {
                    showFragment(FRAGMENT_VIDEO)
                    doubleClick(FRAGMENT_VIDEO)
                }
                R.id.action_media -> {
                    showFragment(FRAGMENT_MEDIA)
                }
            }
            true
        }

       /* drawer_layout=findViewById(R.id.drawer_layout) as DrawerLayout
        val toggle=ActionBarDrawerToggle(this,drawer_layout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close)
        drawer_layout!!.addDrawerListener(toggle)
        toggle.syncState()*/

    }

    fun doubleClick(index:Int){
        val secondClickTime=System.currentTimeMillis()
        if((secondClickTime-firstClickTime)<500){
            when(index){

                FRAGMENT_PHOTO ->{

                }
                FRAGMENT_VIDEO -> {

                }
            }
        }else{
            firstClickTime=secondClickTime
        }
    }

    private fun showFragment(index:Int){
       val ft=supportFragmentManager.beginTransaction()
        hideFragment(ft)
        position=index
        when(index){
           /*FRAGMENT_NEWS -> {
              toolbar!!.setTitle(R.string.title_news)
              if(newsTabLayout==null){
                  newsTabLayout = NewsTabLayout.getInstance()
                  ft.add(R.id.container, newsTabLayout, NewsTabLayout::class.java.name)
              }else{
                  ft.show(newsTabLayout)
              }
           }*/
           FRAGMENT_PHOTO -> {
               toolbar!!.setTitle(R.string.title_photo)
               if(homeTabLayout ==null){
                   homeTabLayout = HomeTabLayout.getInstance()
                   ft.add(R.id.container, homeTabLayout, HomeTabLayout::class.java.name)
               }else{
                   ft.show(homeTabLayout)
               }
           }
           FRAGMENT_VIDEO -> {
               toolbar!!.setTitle(R.string.title_video)
               if(searchTabLayout ==null){
                   searchTabLayout = SearchTabLayout.getInstance()
                   ft.add(R.id.container, searchTabLayout, SearchTabLayout::class.java.name)
               }else{
                   ft.show(searchTabLayout)
               }
           }
           FRAGMENT_MEDIA -> {
               toolbar!!.setTitle(R.string.title_media)
               if(meTabLayout ==null){
                   meTabLayout = MeTabLayout.getInstance()
                   ft.add(R.id.container, meTabLayout, MeTabLayout::class.java.name)
               }else{
                   ft.show(meTabLayout)
               }
           }
        }
        ft.commit()
    }

    private fun hideFragment(ft:FragmentTransaction){
        //如果不为空，就先隐藏起来
        if(newsTabLayout!=null){
            ft.hide(newsTabLayout)
        }
        if(homeTabLayout !=null){
            ft.hide(homeTabLayout)
        }
        if(searchTabLayout !=null){
            ft.hide(searchTabLayout)
        }
        if(meTabLayout !=null){
            ft.hide(meTabLayout as Fragment)
        }
    }

    override fun onBackPressed() {
        //再次点击退出
        val currentTime=System.currentTimeMillis()
        if((currentTime-exitTime)<2000){
            super.onBackPressed()
        }else{
            Toast.makeText(this,R.string.double_click_exit,Toast.LENGTH_SHORT).show()
            exitTime=currentTime
        }
    }

  /*  override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_activity_main, menu)
        return true
    }*/

   /* override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_search) {
           //跳转到搜索页面
        }
        return super.onOptionsItemSelected(item)
    }*/

    /*override fun onNavigationItemSelected(item: MenuItem): Boolean {
        //
        val id=item.itemId
        when(id){
            R.id.nav_switch_night_mode ->{

            }
            R.id.nav_setting ->{

            }
            R.id.nav_share -> {

            }
        }
        return false
    }*/


    fun verifyStoragePermissions(activity: Activity) {
            try {
                //检测是否有写的权限
                val permission = ActivityCompat.checkSelfPermission(activity,
                        "android.permission.WRITE_EXTERNAL_STORAGE")
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
    }

}
